<script setup>
import { ref, watch, nextTick, shallowRef, onBeforeUnmount } from "vue";
import { upload, deleteFile } from "@/api/file";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import { SlateElement } from "@wangeditor/editor";
import {
  getPolicyDetail,
  addPolicy,
  updatePolicy,
  deletePolicy,
} from "@/api/policy";

import { findDeletedImagesWithArrayMethods } from "@/utils/getRemovedImages";
// 抽屉显隐
const visible = ref(false);
const mode = ref("add");

// 表单数据
const policyForm = ref({
  title: "",
  policyType: "",
  status: 1,
  content: "",
});
// 存储用户数据
const currentPolicy = ref({ ...policyForm.value });

// 暴露的方法
const handleOpen = async (row, tag) => {
  mode.value = tag;
  visible.value = true;
  if (mode.value === "edit" || mode.value === "view") {
    const response = await getPolicyDetail(row.policyId);
    currentPolicy.value = response.data.data;
  } else {
    currentPolicy.value = { ...policyForm.value };
  }
};
// 暴露给父组件
defineExpose({
  handleOpen,
});

const emit = defineEmits(["save"]);

// 绑定表单实例
const form = ref(null);

// 状态选项
const statusOptions = [
  { label: "正常", value: 1 },
  { label: "禁用", value: 0 },
];

// 编辑器内容（双向绑定）
const html = ref("");

// 编辑器实例（必须用 shallowRef）
const editor = shallowRef(null);
// 标记编辑器是否已初始化
const isEditorInitialized = ref(false);
// 模式（default 或 simple）
const editorMode = ref("default");

// 工具栏配置
const toolbarConfig = ref({
  exclude: [],
});

const imageElement = {
  ...SlateElement,
  src: "图片地址",
  alt: "图片描述",
  url: "图片链接",
  href: "跳转链接",
};
// 存储输出的图片
const imageList1 = ref([]);
function customCheckImageFn(src, alt, url) {
  if (!src) {
    return; // 返回 undefined，阻止插入且不提示
  }
  if (src.indexOf("http") !== 0) {
    return "图片网址必须以 http/https 开头"; // 返回错误信息，阻止插入并提示
  }
  return true; // 检查通过，允许插入图片
}

// 转换图片链接
function customParseImageSrc(src) {
  if (src.indexOf("http") !== 0) {
    return `http://${src}`; // 补全 http 协议头
  }
  return src; // 已包含协议头，直接返回
}

// 编辑器配置
const editorConfig = ref({
  placeholder: "请输入内容...",
  // 上传图片配置
  MENU_CONF: {
    uploadImage: {
      async customUpload(file, insertFn) {
        const formData = new FormData();
        formData.append("file", file);
        const response = await upload(formData);
        insertFn(response.data.data, file.name, file.size);
      },
    },
    insertImage: {
      onInsertedImage(imageNode) {
        // 移除 ImageElement | null 类型注解
        if (imageNode == null) return; // 处理空值情况
        // 直接解构对象属性（JS 会自动适配对象结构）
        const { src, alt, url, href } = imageNode;
        imageList1.value.push({ src });
        console.log("inserted image", src, alt, url, href);
      },
      checkImage: customCheckImageFn, // 保留校验函数引用（支持 async 函数）
      parseImageSrc: customParseImageSrc, // 保留链接转换函数引用（支持 async 函数）
    },
  },
});

// 编辑器创建完成回调
const handleCreated = (editorInstance) => {
  editor.value = editorInstance;
  isEditorInitialized.value = true;
};

// 编辑器销毁回调
const handleDestroyed = () => {
  editor.value = null;
  isEditorInitialized.value = false;
};

// 点击提交按钮
const handleSubmit = async () => {
  await form.value.validate();
  if (mode.value == "add") {
    const res = await addPolicy(currentPolicy.value);
    ElMessage({
      message: "添加成功",
      type: "success",
      plain: true,
    });
    currentPolicy;
  } else if (mode.value == "edit") {
    console.log(currentPolicy.value);

    const res = await updatePolicy(currentPolicy.value);
    ElMessage({
      message: "修改成功",
      type: "success",
      plain: true,
    });
  }
  handleClose();
  // 触发父组件的 save 事件
  emit("save", mode.value);
};
// DOM销货前，销毁富文本编辑器
onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy();
  }
});

// 关闭抽屉
const handleClose = () => {
  if (editor.value) {
    const imageList2 = editor.value.getElemsByType("image");
    const deletedImages = findDeletedImagesWithArrayMethods(
      imageList1.value,
      imageList2
    );
    if (deletedImages.length) {
      deletedImages.forEach(async (value) => {
        const res = await deleteFile(value.src);
      });
    }
  }
  // 关闭抽屉
  visible.value = false;
  // 重置表单
  if (form.value) {
    form.value.resetFields();
  }
  // 清空富文本编辑器内容
};
</script>

<template>
  <el-drawer
    v-model="visible"
    :title="
      mode === 'add' ? '添加政策' : mode === 'edit' ? '编辑政策' : '查看政策'
    "
    size="50%"
    :destroy-on-close="true"
    @close="handleClose"
  >
    <el-form
      ref="form"
      :model="currentPolicy"
      :rules="{
        title: [{ required: true, message: '请输入政策标题', trigger: 'blur' }],
        policyType: [
          { required: true, message: '请输入政策类型', trigger: 'blur' },
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      }"
      label-width="80px"
    >
      <el-form-item label="政策标题" prop="title">
        <el-input v-model="currentPolicy.title" :disabled="mode === 'view'" />
      </el-form-item>

      <el-form-item label="政策类型">
        <el-input
          v-model="currentPolicy.policyType"
          :disabled="mode === 'view'"
          placeholder="请输入政策类型"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="currentPolicy.status"
          :disabled="mode === 'view'"
          placeholder="请选择状态"
        >
          <template #prefix>
            <el-tag :type="currentPolicy.status === 1 ? 'success' : 'danger'">
              {{ currentPolicy.status === 1 ? "正常" : "禁用" }}
            </el-tag>
          </template>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="政策内容" v-if="mode !== 'view'">
        <div class="editor-container">
          <!-- 工具栏：仅在编辑器实例存在时渲染 -->
          <Toolbar
            v-if="editor"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="editorMode"
          />

          <!-- 编辑器内容区域 -->
          <Editor
            v-model="currentPolicy.content"
            :editor="editor"
            :defaultConfig="editorConfig"
            :mode="editorMode"
            @onCreated="handleCreated"
            @onDestroyed="handleDestroyed"
            class="editor-content"
          />
        </div>
      </el-form-item>
      <el-form-item label="政策内容" v-else>
        <div class="view-content" v-html="currentPolicy.content"></div>
      </el-form-item>
    </el-form>

    <div style="text-align: right; margin-top: 20px">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" v-if="mode !== 'view'">
        {{ mode === "add" ? "新增" : "保存" }}
      </el-button>
    </div>
  </el-drawer>
</template>

<style scoped>
::v-deep .el-drawer__body {
  padding-bottom: 60px;
}

.view-content {
  width: 100%;
  min-height: 400px;
  overflow-y: auto;
  border: 1px solid #f5f5f5;
  padding: 10px;
}

/* 富文本编辑器样式 */
.editor-container {
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
}

/* 工具栏样式 */
::v-deep .w-e-toolbar {
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #e5e7eb !important;
  background-color: #f9fafb !important;
  padding: 8px 12px !important;
}

::v-deep .w-e-toolbar .w-e-menu {
  margin: 0 4px !important;
  padding: 4px 8px !important;
  border-radius: 4px !important;
}

::v-deep .w-e-toolbar .w-e-menu:hover {
  background-color: #eff6ff !important;
}

/* 编辑区域样式 */
.editor-content {
  width: 100%;
  min-height: 400px;
  box-sizing: border-box;
  background-color: #fff;
}

::v-deep .w-e-text-container {
  width: 100% !important;
  border: none !important;
  box-shadow: none !important;
}

/* 适配查看模式 */
:deep(.w-e-text-container[contenteditable="false"]) {
  background-color: #f9fafb;
  border-radius: 0 0 6px 6px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .editor-content {
    min-height: 200px;
  }
}
</style>
